import { Watermark, Spin } from 'antd'
import classNames from 'classnames'
import styles from './examination.module.scss'
import { Flex, Radio, Space, Checkbox, message, Modal } from 'antd'
import { startCountdown } from '@/utils/countDownTimer'
import { useEffect, useState } from 'react'
import { useLocation } from 'react-router-dom'
import { getQuestion, sorce } from '@/api/question'
import { useSelector } from 'react-redux'
import { useNavigate } from 'react-router-dom'
import React from 'react'

type questionObj = {
  id: number
  title: string
  options: { option: string; content: string; label: string; value: string }[]
  type: string | number
  serial: number
  choice: string
}

const Examination = () => {
  /**
   * 变量
   */
  const [remainingTime, setRemainingTime] = useState(60 * 60)
  const routeLocation = useLocation()
  const params = new URLSearchParams(routeLocation.search)
  const flag = parseInt(params.get('flag') || '1')
  const [currentQuestion, setCurrenQuestion] = useState<questionObj>() // 当前展示题目
  const [questionList, setQuestionList] = useState<questionObj[]>([]) // 题目列表
  const [tempList, setTempList] = useState<questionObj[]>([]) // 临时题目列表
  const single: number[] = Array.from({ length: 20 }, (_, index) => index)
  const multiple: number[] = Array.from({ length: 10 }, (_, index) => index)
  const judgment: number[] = Array.from({ length: 10 }, (_, index) => index)
  const [messageApi, messageContent] = message.useMessage()
  const { userInfo } = useSelector((state: RootState) => state.handleUser)
  const [isModalOpen, setIsModalOpen] = useState(false) // 对话框相关
  const navigate = useNavigate()
  const [tips, setTips] = useState('')
  const [spinning, setSpinning] = React.useState<boolean>(false) // loading

  /**
   * 获取问题
   */
  const fetchQuestion = async () => {
    // 获取题目
    const res = await getQuestion({ type: -1 })
    const handler_list = res.data.map((item: questionObj) => {
      // if (item.type === '2') {
      const hanlder_m_options = item.options.map(option => ({
        label: option.content,
        value: option.option
      }))

      return {
        ...item,
        choice: '',
        options: hanlder_m_options
      }
      // }
      // return item
    })

    setCurrenQuestion({ ...handler_list[0], serial: 1, choice: '' })
    // setQuestionList(handler_list)
    // setTempList(handler_list)
    // 创建独立的副本
    const tempListCopy = JSON.parse(JSON.stringify(handler_list))
    const questionListCopy = JSON.parse(JSON.stringify(handler_list))

    setTempList(tempListCopy)
    setQuestionList(questionListCopy)
  }

  /**
   * 倒计时
   */
  useEffect(() => {
    const countdown = startCountdown({
      initialDuration: 60 * 60,
      onTimeout: () => {
        console.log('倒计时结束')
        // 处理倒计时结束的逻辑
      }
    })
    // 在每次剩余时间更新时更新状态
    const intervalId = setInterval(() => {
      setRemainingTime(countdown.getRemainingTime())
    }, 1000)
    // document.addEventListener('visibilitychange', function () {
    //   intervalId = setInterval(() => {
    //     setRemainingTime(countdown.getRemainingTime())
    //   }, 1000)
    // })

    fetchQuestion()

    return () => {
      countdown.stop(), clearInterval(intervalId)
    }
  }, [])
  const formatTime = (timeInSeconds: number) => {
    const minutes = Math.floor(timeInSeconds / 60)
    const seconds = timeInSeconds % 60
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
  }

  /**
   * 点击答题卡
   */
  const selectQuestion = (index: number) => {
    setCurrenQuestion({ ...questionList[index], serial: index + 1, choice: '' })
  }

  /**
   * 选择答案
   */
  const selected = (e: string[] | string) => {
    const answer = e
    if (currentQuestion) {
      currentQuestion.choice = answer as string
      setCurrenQuestion({ ...currentQuestion, choice: answer as string })

      if (tempList[currentQuestion.serial - 1].id === currentQuestion.id) {
        const updatedTempList = [...tempList]
        updatedTempList[currentQuestion.serial - 1].choice = answer as string
        setTempList(updatedTempList)
      }
    }
  }

  /**
   * 下一题
   * @param type 2:确定  1：下一题
   */
  const next = (type: number) => {
    if (currentQuestion) {
      if (currentQuestion?.serial >= questionList.length) {
        const updatedTempList = [...tempList]
        const updatedQuestionList = [...questionList]
        updatedQuestionList[currentQuestion.serial - 1].choice = updatedTempList[currentQuestion.serial - 1].choice
        setQuestionList(updatedQuestionList)
        return messageApi.info('已经是最后一题了，可以检查看看有没有漏题的呦，没问题就可以交卷了')
      }
      if (type == 2) {
        if (currentQuestion) {
          if (questionList[currentQuestion.serial - 1].id === currentQuestion.id) {
            const updatedTempList = [...tempList]
            const updatedQuestionList = [...questionList]
            const t_o = updatedTempList[currentQuestion.serial - 1].choice
            updatedQuestionList[currentQuestion.serial - 1].choice = Array.isArray(t_o) ? t_o.join('') : t_o
            setQuestionList(updatedQuestionList)
          }
        }
      }
      if (currentQuestion) setCurrenQuestion({ ...tempList[currentQuestion.serial], serial: currentQuestion.serial + 1 })
    }
  }

  /**
   * 上一题
   */
  const prev = () => {
    if (currentQuestion) {
      if (currentQuestion.serial <= 1) {
        return messageApi.warning('已经是第一题了喂')
      }
      setCurrenQuestion({ ...tempList[currentQuestion.serial - 1 - 1], serial: currentQuestion.serial - 1 })
    }
  }

  /**
   * 交卷
   */
  // 交卷打分
  const sub_score = async () => {
    setSpinning(true)
    const strJson = JSON.stringify(questionList)
    const res = await sorce({ questionList: strJson, flag: flag }, userInfo.id)
    if (res.code < 200 || res.code > 399) {
      messageApi.error('发生了错误，' + res.message)
    }

    messageApi.success('交卷成功')
    setSpinning(false)
    setTimeout(() => {
      navigate('/afterexam', { state: { score: res.data.score, questionList: tempList }, replace: true })
    }, 500)
  }
  // 提交按钮
  const submit = async () => {
    const hasEmptyChoice = questionList.some(item => {
      return item.choice === ''
    })

    if (hasEmptyChoice) {
      setTips('题目尚未答完，就交卷啦？嗯？')
      return setIsModalOpen(true)
    }
    // 全部答完了
    sub_score()
  }

  useEffect(() => {
    // 时间到了
    // const s = async () => {
    //   const strJson = JSON.stringify(questionList)
    //   const res = await sorce({ questionList: strJson, flag: flag }, userInfo.id)
    //   if (res.code < 200 || res.code > 399) {
    //     messageApi.error('发生了错误，' + res.message)
    //   }

    //   messageApi.success('交卷成功')
    // }
    if (remainingTime <= 0) {
      sub_score()
    }
  }, [remainingTime])

  /**
   * 对话框相关
   */
  const handleOk = async () => {
    setIsModalOpen(false)
    // 时间没打，题没答完 ，继续交卷
    sub_score()
  }

  const handleCancel = () => {
    setIsModalOpen(false)
  }

  return (
    <>
      {messageContent}
      <Spin spinning={spinning} fullscreen tip="评分中" />
      <Modal title="提示" okText={'继续交卷'} cancelText={'取消'} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        {/* <p>题目尚未答完，就交卷啦？嗯？</p> */}
        <p>{tips}</p>
      </Modal>
      <Watermark height={30} width={130} content="GG考试" style={{ height: '100%' }}>
        <div className={classNames(styles.box_exam)}>
          <Flex vertical={false} style={{ height: '100%' }}>
            <div className={classNames(styles.left)}>
              <Flex vertical={false} align="center" justify="space-between">
                <div className={classNames(styles.header)}>
                  欢迎来到GG考试， 本次考试为
                  <span style={{ fontWeight: '700' }}>{flag === 1 ? '模拟考试' : '真实考试'}</span>
                </div>
                <div className={classNames(styles.time)}>时间剩余：{formatTime(remainingTime)}</div>
              </Flex>
              <div className={classNames(styles.tips)} style={{ marginBottom: '10px' }}>
                共40题 20到单选题（2分/道），10到多选题（3分/道），10到判断题（3分/道）共100分
                <div style={{ fontSize: '12px', color: 'var(--secondary-color)' }}>温馨提示: 每次作答完成请点击确定</div>
              </div>
              <div className={classNames(styles.question_area)}>
                <div className={classNames(styles.title)}>
                  {currentQuestion?.serial}. {currentQuestion?.title}
                </div>
                <div className={classNames(styles.options)}>
                  {/* 单或判断 选项 */}
                  {(currentQuestion?.type === '1' || currentQuestion?.type === '3') && (
                    <Radio.Group
                      onChange={e => selected(e.target.value)}
                      options={currentQuestion?.options}
                      style={{ display: 'flex', width: '100%', flexDirection: 'column', gap: '1.25rem' }}
                      value={currentQuestion.choice}
                    ></Radio.Group>
                  )}
                  {/* 多选题的选项 */}
                  {currentQuestion?.type === '2' && (
                    <Checkbox.Group
                      onChange={e => selected(e)}
                      style={{ width: '100%', flexDirection: 'column', gap: '1.25rem' }}
                      options={currentQuestion?.options}
                      value={currentQuestion.choice as unknown as string[]}
                    ></Checkbox.Group>
                  )}
                </div>
                <div className={classNames(styles.box_btn)}>
                  <Flex align="center">
                    <div className={classNames(styles.pre, styles.btn)} onClick={() => prev()}>
                      上一题
                    </div>
                    <div className={classNames(styles.confirm, styles.btn)} onClick={() => next(2)}>
                      确定
                    </div>
                    <div className={classNames(styles.options, styles.btn)} onClick={() => next(1)}>
                      下一题
                    </div>
                  </Flex>
                </div>
              </div>
            </div>
            <div className={classNames(styles.right)}>
              <div className={classNames(styles.submit)} onClick={submit}>
                交卷
              </div>
              {questionList && (
                <div className={classNames(styles.answer_card)}>
                  {/* 单选题 */}
                  一、单选题
                  <Space size={[6, 16]} wrap>
                    {single.map((item, index) => {
                      return (
                        <div
                          className={classNames(styles.serial, {
                            [styles.answered_serial]: questionList[item] && questionList[item].choice !== ''
                          })}
                          key={index}
                          onClick={() => selectQuestion(item)}
                        >
                          {item + 1}
                        </div>
                      )
                    })}
                  </Space>
                  {/* 多选题 */}
                  <div style={{ margin: '1.25rem 0' }}>
                    二、多选题
                    <Space size={[6, 16]} wrap>
                      {multiple.map((item, index) => (
                        <div
                          className={classNames(styles.serial, {
                            [styles.answered_serial]: questionList[item] && questionList[item + 20].choice !== ''
                          })}
                          key={index}
                          onClick={() => selectQuestion(item + 20)}
                        >
                          {item + 21}
                        </div>
                      ))}
                    </Space>
                  </div>
                  {/* 判断题 */}
                  三、判断题
                  <Space size={[6, 16]} wrap>
                    {judgment.map((item, index) => (
                      <div
                        className={classNames(styles.serial, {
                          [styles.answered_serial]: questionList[item] && questionList[item + 30].choice !== ''
                        })}
                        key={index}
                        onClick={() => selectQuestion(item + 30)}
                      >
                        {item + 31}
                      </div>
                    ))}
                  </Space>
                </div>
              )}
            </div>
          </Flex>
        </div>
      </Watermark>
    </>
  )
}

export default Examination
